﻿define([
    'require',
    'angular',
    'underscore'
], function (require, angular, _) {
    return function ($scope,$rootScope, Resource, $dataSourceManager, GillionMsg, $location,$compile, $timeout, $routeParams,RuleSerivce,$http,RuleEditService) {
        $scope.testId = $location.search().testId;
        RuleSerivce.readyData();
        RuleSerivce.setVariableScope(2);
        $rootScope.headerPackageId=$routeParams.packageId;
        $scope.executeRule=[];
        RuleSerivce.promises().then(function () {
            if($scope.testId) {
                $http({
                    method: 'GET',
                    url: '/grule-manager/test-log/package',
                    params: {
                        testId: $scope.testId
                    }
                }).success(function (resp) {
                    if (resp.data != null) {
                        $scope.executeRule = resp.data;
                    }
                });
            }


            $scope.status=$rootScope.currPackage.status;
            $scope.businessModelId=$rootScope.currPackage.businessModelId;
            //加载模型
            Resource("/grule-manager/businessModelAttribute/list/:id", {id: '@id'}).get({
                id:  $scope.businessModelId
            }, function (response) {
                if(response.data!=null){
                    $scope.modelAttributes=response.data;
                }
            });
            Resource("/grule-manager/data_dict/rule/dict/:id",{id: '@id'}).get({ id:  $rootScope.currProjcet.id}, function (response) {
                if(response.data!=null){
                    $scope.dicts=response.data;
                }
            });

            $scope.copyAssemblyRule=function(menu){
                GillionMsg.confirm('提示信息', '确认复制当前规则集？',
                    function (r) {
                        if(r){
                            $http({
                                url:"/grule-manager/ruleAssembly/copyRuleAssembly",
                                method:"GET",
                                params:{
                                    id:menu.id,
                                }
                            }).success(function(resp){
                                if(resp.success) {
                                    RuleSerivce.getRulePackageMenu($scope.packageId);
                                }
                            });
                        }else{
                            return false;
                        }
                    })
            };

            var response=$rootScope.currAssembly
            $scope.assemblyName = response.name;
            if(response.conditions!=null&&response.conditions!="undefined"&&response.conditions!="{}") {
                $scope.context = response.conditions;
                var json = eval('(' + $scope.context + ')');
                var resultList = RuleEditService.showRule(json);
                RuleEditService.setHtml($scope,resultList,"condition");
            }else{
                RuleEditService.addConditionRow($scope,"","",true);
            }

            if (document.cookie.match(/scrollTop=([^;]+)(;|$)/) != null) {
                var arr = document.cookie.match(/scrollTop=([^;]+)(;|$)/); //cookies中不为空，则读取滚动条位置
                //document.documentElement.scrollTop = parseInt(arr[1]);
                document.getElementById("ruleMes").scrollTop = parseInt(arr[1]);
            }
        });

        $scope.selectPackage= function() {
            var url ="#/projects/"+$scope.currProjcet.id+"/packages/"+$scope.currPackage.id+"?testId="+$scope.testId;
            if($scope.isMes){
                GillionMsg.confirm('提示信息', '当前配置未保存，是否离开？',
                    function (r) {
                        if(r){
                            window.location.href=url;
                        }else{
                            return false;
                        }
                    })
            }
            window.location.href=url;
        }
        $scope.beforeSelect= function(menu) {
            $scope.saveScroll();
            if($scope.isMes){
                GillionMsg.confirm('提示信息', '当前配置未保存，是否离开？',
                    function (r) {
                        if(r){
                            $scope.select(menu);
                        }else{
                            return false;
                        }
                    })
            }else{
                $scope.select(menu);
            }
        }

        $scope.select = function(menu){
            if(menu.decisionTable){
                RuleSerivce.setCurrentDecisionTable(menu);
                RuleSerivce.setVariableScope(4);
            }
            else{
                RuleSerivce.setCurrentAssembly(menu);
                RuleSerivce.setVariableScope(2);
            }
            var url="";
            if(menu.type==0){
                url="#/projects/"+$scope.currProjcet.id+"/packages/"+$scope.packageId+"/assemblys/"+menu.id+"?testId="+$scope.testId;
            }else if(menu.type==1){
                url="#/projects/"+$scope.currProjcet.id+"/packages/"+$scope.packageId+"/decisionTables/"+menu.id+"?testId="+$scope.testId;
            }else{
                url="#/projects/"+$scope.currProjcet.id+"/packages/"+$scope.packageId+"/decisionTrees/"+menu.id+"?testId="+$scope.testId;
            }
            window.location.href=url;
        };

        $scope.beforeSelectRule= function(rule,menu) {
            $scope.saveScroll();
            if($scope.isMes){
                GillionMsg.confirm('提示信息', '当前配置未保存，是否离开？',
                    function (r) {
                        if(r){
                            $scope.selectRule(rule,menu);
                        }else{
                            return false;
                        }
                    })
            }else{
                $scope.selectRule(rule,menu);
            }
        }

        $scope.saveScroll=function (){
            var scrollPos;
            if (typeof document.getElementById("ruleMes") != 'undefined') {
                scrollPos = document.getElementById("ruleMes").scrollTop;
            }
            document.cookie = "scrollTop=" + scrollPos; //存储滚动条位置到cookies中
        };

        $scope.selectRule = function(rule,menu){
            $http({
                url:"/grule-manager/ruleAssembly/"+rule.ruleAssemblyId,
                method:"GET",
                params:{
                    id:rule.ruleAssemblyId
                }
            }).success(function(resp){
                RuleSerivce.setCurrentAssembly(resp);
            });
            RuleSerivce.setCurrentRule(rule);
            RuleSerivce.setVariableScope(3);
            var url="";
            if(menu.type==0){
                url="#/projects/"+$scope.currProjcet.id+"/packages/"+$scope.packageId+"/assemblys/"+menu.id+"/rules/"+rule.id+"?testId="+$scope.testId;
            }else if(menu.type==1){
                url="#/projects/"+$scope.currProjcet.id+"/packages/"+$scope.packageId+"/decisionTables/"+menu.id+"/rules/"+rule.id+"?testId="+$scope.testId;
            }else{
                url="#/projects/"+$scope.currProjcet.id+"/packages/"+$scope.packageId+"/decisionTrees/"+menu.id+"/rules/"+rule.id+"?testId="+$scope.testId;
            }
            window.location.href=url;
        };

        angular.element('.engine-tab li:first').trigger('click');
        $scope.id=$routeParams.assemblyId;
        $scope.packageId = $routeParams.packageId;
        $scope.projectId = $routeParams.projectId;
        RuleSerivce.getRulePackageMenu($scope.packageId);
        Resource("/grule-manager/projects/"+$scope.projectId).get({},function(project){
            $scope.currProjcet = project;
        });

        $scope.count=1;
        $scope.countCondition=1;
        $scope.nowClick = 1;
        $scope.jsonContext={};
        $scope.showSign=false;
        $scope.showProperty=false;
        $scope.showEntry=false;
        $scope.showNone=true;
        $scope.showAllCondition=false;
        $scope.showMethod=false;
        $scope.translate=[{">":"大于"},{">=":"大于等于"},{"==":"等于"},{"<":"小于"},{"<=":"小于等于"},{"!=":"不等于"},{"+":"加"},
            {"-":"减"},{"*":"乘"},{"/":"除"},{"(":"("},{")":")"}];
        $scope.conditionRows=[];
        $scope.conditions=[];

        $scope.createRule=function(){
            GillionMsg.showUrl({
                title: '新建规则',
                url: '/html2/rule/create/createRule',
                width: 400,
                height:300,
                data: $scope.id,
                onClose: function (data) {
                    if (data.success) {
                        RuleSerivce.getRulePackageMenu($scope.packageId);
                    }
                }
            });
        };

        var ruleAssemblyResource = Resource("/grule-manager/ruleAssembly/:id", {
            id: "@id"
        });

        //加载变量
        function loadVariables() {
            Resource("/grule-manager/variables/assembly/:id", {id: '@id'}).get({
                id:  $scope.id
            }, function (response) {
                if(response.data!=null){
                    $scope.variables=response.data;
                }
            });
        }
        loadVariables();

        angular.element(document).off('refresh.variables').on('refresh.variables', function() {
            loadVariables();
        });

        //isButton 是否需要显示按钮
        $scope.addConditionRow=function(type,conditionList,isButton){
            RuleEditService.addConditionRow($scope,type,conditionList,isButton);
        };

        $scope.change=function (click){
            RuleEditService.change($scope,click);
        };

        $scope.selectLogicalSign=function(sign,mes,num){
            $scope.count++;
            var node   = angular.element("#symbol" + num).parent().empty();
            node.append(
                $compile(
                    "<a href='javascript:void(0)' ng-click='change("+$scope.count+")' name='node'  id='symbol"+$scope.count+"' value='{&apos;oper&apos;:&apos;"+sign+"&apos;}'>"+mes+"<i class='icon-engine-down-a'></i></a>"
                )($scope)
            )
        };

       /* $scope.addCondition=function(count){
            $scope.countCondition++;
            init();
            angular.element("#addRow" + count).append(
                $compile(
                    "<span  id='click"+$scope.countCondition+"' ><button type='button' name ='addButton' id='showCondition"+$scope.countCondition+"' ng-click='show("+$scope.countCondition+",&apos;button&apos;)' class='engine-btn-default'>点击选择</button></span>"
                )($scope)
            );
        };*/

        $scope.removeCondition = function(num){
            angular.element("#click" + num).remove();
        };

        $scope.removeRowCondition=function(index){
            $scope.conditionRows.splice(index, 1);
        };
        $scope.copyCRow=function(index){
            RuleEditService.copyCRow($scope,index);
        };

        $scope.addRowCondition=function(index){
            RuleEditService.addRowCondition($scope,index);
        };

        $scope.show=function(type,model,showType){
            RuleEditService.show($scope,type,model,showType);
        };

        $scope.viewObject = function (id,margin) {
            RuleEditService.viewObject($scope,id,margin)
        };

        $scope.addButton= function(){
            RuleEditService.addButton($scope);
        }

        $scope.addEntry=function(){
            RuleEditService.addEntry($scope);
        };

        $scope.addDict=function(item){
            RuleEditService.addDict($scope,item);
        };

        $scope.addSign=function(value){
            RuleEditService.addSign($scope,value);
        };
        $scope.addModel=function(value){
            RuleEditService.addModel($scope,value);
        };

        $scope.addVariable=function(value){
            RuleEditService.addVariable($scope,value);
        };

        $scope.addMethod=function(value,text){
            RuleEditService.addMethod($scope,value,text);
        };

        $scope.addFront=function(value){
            RuleEditService.addFront($scope,value);
        };

        $scope.addBehind=function(value){
            RuleEditService.addBehind($scope,value);
        };

        $scope.save=function(){
            $scope.isMes=false;
            var list=[];
            var nodes = $("a[name='node']");
            angular.forEach(nodes,function(node){
                list.push( eval("(" + node.attributes.value.nodeValue + ")"));
            });
            var result = RuleEditService.getCondition(list);
            var ruleAssembly={};
            ruleAssembly.id= $scope.id;
            ruleAssembly.conditions= JSON.stringify(result);
            if(ruleAssembly.conditions==null||ruleAssembly.conditions==undefined){
                ruleAssembly.conditions="{}";
            }
            ruleAssemblyResource.update(ruleAssembly, function (response) {
                if(response.success){
                    GillionMsg.alert("提示","修改成功！");
                }
            });
        };
        $scope.deleteMenu=function(menu){
            var path = 'ruleAssembly';
            if (menu.decisionTable) {
                path = 'decision-tables';
            }
            GillionMsg.confirm('提示信息', '是否确定删除？',
                function (r) {
                    if(r==true) {
                        Resource("/grule-manager/" + path + "/:id", {
                            id: "@id"
                        }).delete({
                            id: menu.id
                        }, function (response) {
                            if (response.success) {
                                GillionMsg.alert('提示', '删除成功', function(){
                                    angular.element(document).trigger('refresh.menu');
                                    window.location.href='/html2/home#/projects/' + $scope.projectId + '/packages/' +  $scope.packageId;
                                });
                            }
                        });
                    }
                }
            );
        };

        $scope.deleteRule=function(id){
            GillionMsg.confirm('提示信息', '是否确定删除？',
                function (r) {
                    if (r == true) {
                        Resource("/grule-manager/rule/:id", {
                            id: "@id"
                        }).delete({
                            id: id
                        }, function (response) {
                            if(response.success){
                                GillionMsg.alert('提示', '删除成功', function(){
                                    angular.element(document).trigger('refresh.menu');
                                    window.location.href='/html2/home#/projects/' + $scope.projectId + '/packages/' +  $scope.packageId;
                                });
                            }
                        });
                    }
                }
            )
        }


        /*function checkRule(){
            var  errorMes= $("[name='errorMes']");
            for(var i=0;i<errorMes.length;i++){
                errorMes.remove();
            }
            var nodes = $("[name='rowVariable']");
            for(var i=0;i<nodes.length;i++){
                var typeList=[];
                var valueList=[];
                var idList=[];//通过匹配typeList 找出对应不符合要求的节点
                var spanNodes = nodes[i].children;
                //现将所有的type 放入到 list中，后续判断
                for(var j=0;j<spanNodes.length;j++){
                    /!*spanNodes.attributes.type.nodeValue*!/
                    var child =spanNodes[j].children;
                    if(child[0].attributes.type!=undefined&&child[0].attributes.value!=undefined) {
                        var type = child[0].attributes.type.nodeValue;
                        if(type!="button"&&child[0].attributes.value.nodeValue.indexOf("(")<0&&child[0].attributes.value.nodeValue.indexOf(")")<0) {
                            typeList.push(type);
                            idList.push(child[0].id);
                            valueList.push(child[0].attributes.value.nodeValue);
                        }
                    }
                }
                //根据上个步骤产生的typelist进行判断校验
                for(var j=0;j<typeList.length;j++){
                    if(j!=0){
                        //连续两个符号
                        if(typeList[j-1]==="sign"&&(typeList[j]==="sign"||typeList[j]==="method")){
                            angular.element("#" + idList[j]).parent().parent().parent().append(
                                "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                            );
                            break;
                        }
                        //连续两个变量、模型、输入值或方法后面跟这三个类型
                        else if(typeList[0]!=="setValue"&&(typeList[j-1]==="variable"||typeList[j-1]==="property"||typeList[j-1]==="entry")&&(typeList[j]==="variable"||typeList[j]==="property"||typeList[j]==="entry")){
                            var status="abnormal"
                            for(var i=0;i<j;i++){
                                if(typeList[i]=="component"){
                                    status="normal";
                                }
                            }
                            if(status=="abnormal"){
                                angular.element("#" + idList[j]).parent().parent().parent().append(
                                    "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                                );
                            }
                            break;
                        }
                        //设置变量或者属性时，不可连续三个属性或者变量等结合
                        if(j>1&&typeList[0]==="setValue"&&(typeList[j-2]==="variable"||typeList[j-2]==="property"||typeList[j-2]==="entry"||typeList[j-2]==="method")&&(typeList[j-1]==="variable"||typeList[j-1]==="property"||typeList[j-1]==="entry"||typeList[j-1]==="method")&&(typeList[j]==="variable"||typeList[j]==="property"||typeList[j]==="entry")){
                            angular.element("#" + idList[j]).parent().parent().parent().append(
                                "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                            );
                            break;
                        }
                        //设置变量与属性时，后面必须跟变量或者模型
                        if(typeList[0]==="setValue"&&typeList[1]!=="variable"&&typeList[1]!=="property"){
                            angular.element("#" + idList[j]).parent().parent().parent().append(
                                "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                            );
                            break;
                        }
                        if(j==typeList.length-1){
                            if(typeList[j]=="sign"){
                                angular.element("#" + idList[j]).parent().parent().parent().append(
                                    "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                                );
                                break;
                            }
                        }
                    }else{
                        if(typeList[j]=="sign"){
                            angular.element("#" + idList[j]).parent().parent().parent().append(
                                "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                            );
                            break;
                        }
                    }
                }
            }
        }*/
        //type  按钮或者节点   state 编辑状态还是保存后状态，由于传入的节点不同，进行判断
        window.showEdit=function(type){
            RuleEditService.showEdit($scope,type);
        };
        //type  按钮或者节点   state 编辑状态还是保存后状态，由于传入的节点不同，进行判断
        window.closeEdit=function(type,state){
            RuleEditService.closeEdit(type,state);
        };
        //添加括号方法
        $scope.addBracket=function(num){
            var nodesList=[];
            //$("#bracket").css("display", "block");
            var  rowNodes =$("[name='rowC']");
            for(var i=0;i<rowNodes.length;i++){
                var divNodes = rowNodes[i].children;// <div>
                var spanNodes = divNodes[1].children; //<span>
                for(var j=0;j<spanNodes.length;j++){
                    var aNode = spanNodes[j].children;
                    nodesList.push(aNode[0]);
                }
            }
            for(var i=0;i<nodesList.length;i++){
                if(nodesList[i].attributes.type!=undefined) {
                    if (nodesList[i].attributes.type.nodeValue == "property" || nodesList[i].attributes.type.nodeValue == "variable" || nodesList[i].attributes.type.nodeValue == "entry") {
                        //nodesList[i].addClass("attribute-kuoh-c");
                        var node = angular.element("#" + nodesList[i].id);
                        node.parent().addClass("attribute-kuoh");
                        node.after(
                            $compile(
                                "<div class='left' name ='leftBracket'><a href='javascript:void(0)' ng-click='addLeftBracket(&apos;" + nodesList[i].id + "&apos;)'>(</a></div>"
                            )($scope)
                        )
                    }
                }
            }
            showLeftBracket();
        };

        //点击左括号之后显示右括号
        function showRightBracket(nodeId){
            var nodesList=[];
            var startList=[];
            var  rowNodes= $("[name='rowC']");
            for(var i=0;i<rowNodes.length;i++){
                var divNodes = rowNodes[i].children;// <div>
                var spanNodes = divNodes[1].children; //<span>
                for(var j=0;j<spanNodes.length;j++){
                    var aNode = spanNodes[j].children;
                    nodesList.push(aNode[0]);
                }
            }
            for(var i=0;i<nodesList.length;i++){
                if(nodesList[i].id==nodeId){
                    startList=nodesList.slice(i,nodesList.length);
                    break;
                }
            }
            for(var i=0;i<startList.length;i++){
                if(nodesList[i].attributes.type!=undefined) {
                    if (startList[i].attributes.type!=undefined&&(startList[i].attributes.type.nodeValue == "property" || startList[i].attributes.type.nodeValue == "variable" || startList[i].attributes.type.nodeValue == "entry")) {
                        //nodesList[i].addClass("attribute-kuoh-c");
                        var node = angular.element("#" + startList[i].id);
                        node.parent().addClass("attribute-kuoh");
                        node.after(
                            $compile(
                                "<div class='right' name ='rightBracket'><a href='javascript:void(0)' ng-click='addRightBracket(&apos;" + startList[i].id + "&apos;)'>)</a></div>"
                            )($scope)
                        )
                    }
                }
            }
        }

        //添加左括号
        $scope.addLeftBracket= function(nodeId){
            $scope.countCondition++;
            var node =angular.element("#" + nodeId) ;
            var span = node.parent();
            span.before(
                $compile(
                    "<span  id='click" + $scope.countCondition + "'  onmouseleave='closeEdit(&apos;node&apos;)'  onmouseenter='showEdit(&apos;node&apos;)'  ><a href='javascript:void(0)' name='node'  id='node"+$scope.countCondition+"'  ng-click='show(&apos;"+$scope.countCondition+"&apos;,&apos;node&apos;,&apos;sign&apos;)'  type='sign' value='{&apos;oper&apos;:&apos;(&apos;}'>(</a></span>"
                )($scope)
            );

            cleanBracket("left");
            showRightBracket(nodeId);
        };

        //添加右边括号
        $scope.addRightBracket= function(nodeId){
            $scope.countCondition++;
            var node =angular.element("#" + nodeId) ;
            var span = node.parent();
            span.after(
                $compile(
                    "<span  id='click" + $scope.countCondition + "'  onmouseleave='closeEdit(&apos;node&apos;)'  onmouseenter='showEdit(&apos;node&apos;)'  ><a href='javascript:void(0)' name='node'  id='node"+$scope.countCondition+"'  ng-click='show(&apos;"+$scope.countCondition+"&apos;,&apos;node&apos;,&apos;sign&apos;)'  type='sign' value='{&apos;oper&apos;:&apos;)&apos;}'>)</a></span>"
                )($scope)
            );

            cleanBracket("right");
            $("#shadeCondition").css({ display: "none"});
        };

        function showLeftBracket(){
            $("#shadeCondition").css({ display: "block"});
            $("#bracket").css("display", "block");
        }

        //type: left | right | all
        function cleanBracket(type){
            if(type=="left"||type=="all"){
                var  bracketNodes= $("[name='leftBracket']");
                for(var i=0;i<bracketNodes.length;i++){
                    bracketNodes[i].remove();
                }
            }
            if(type=="right"||type=="all"){
                var  bracketNodes= $("[name='rightBracket']");
                for(var i=0;i<bracketNodes.length;i++){
                    bracketNodes[i].remove();
                }
            }
        }

        //点击遮罩还原
        $("#shadeCondition").mouseup(function(){
            RuleEditService.init($scope);
            $("#shadeCondition").css({ display: "none"});
            cleanBracket("all");
            angular.element("#node" + $scope.nowClick).removeClass("attribute-check");
            angular.element("#showCondition" + $scope.nowClick).removeClass("attribute-check");
            angular.element("#showCondition" + $scope.nowClick).html("点击选择");
        });

        $scope.isExecuteRule=function(id){
            if($scope.executeRule.indexOf(id)>-1){
                return true;
            }else{
                return false;
            }
        }
    }
});